<template>
  <div class="video-player">
    <div v-if="isError" class="error-message">
      <span>{{ errorMessage }}</span>
      <t-button size="small" @click="handleRetry">重试</t-button>
    </div>
    <div v-else class="video-container">
      <video
        ref="videoPlayer"
        class="video-js vjs-custom-theme vjs-big-play-centered"
        controls
        preload="auto"
        width="100%"
        height="100%"
        data-setup="{}"
      >
        <source :src="processedVideoUrl" :type="videoType" />
        您的浏览器不支持视频播放
      </video>
    </div>
  </div>
</template>

<script>
import videojs from 'video.js';
import 'video.js/dist/video-js.css';

export default {
  name: 'VideoPlayer',
  props: {
    noteId: {
      type: [String, Number],
      required: true,
    },
    platform: {
      type: String,
      default: 'default',
    },
  },
  data() {
    return {
      player: null,
      isError: false,
      errorMessage: '',
      processedVideoUrl: '',
      videoType: 'video/mp4',
      retryCount: 0,
      maxRetries: 3,
    };
  },
  watch: {
    noteId: {
      immediate: true,
      handler(newId) {
        this.processVideoUrl(newId);
      },
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.initializePlayer();
    });
  },
  beforeDestroy() {
    if (this.player) {
      this.player.dispose();
    }
  },
  methods: {
    processVideoUrl(noteId) {
      if (!noteId) {
        this.handleError('无效的视频ID');
        return;
      }

      this.processedVideoUrl = `http://127.0.0.1:8000/api/xhs/test/?note_id=${noteId}`;
      console.log('Video URL:', this.processedVideoUrl);
    },

    handleError(message) {
      this.isError = true;
      this.errorMessage = message;
      console.error('Video Error:', message);
    },

    async initializePlayer() {
      if (!this.processedVideoUrl) {
        this.handleError('视频地址未设置');
        return;
      }

      try {
        if (this.player) {
          this.player.dispose();
        }

        const options = {
          controls: true,
          autoplay: false,
          preload: 'auto',
          fluid: true,
          responsive: true,
          playbackRates: [0.5, 1, 1.5, 2],
          sources: [
            {
              src: this.processedVideoUrl,
              type: this.videoType,
            },
          ],
          width: '100%',
          height: '100%',
        };

        this.player = videojs(this.$refs.videoPlayer, options, () => {
          console.log('播放器初始化完成');
          this.player.reset();
          this.player.src({
            src: this.processedVideoUrl,
            type: this.videoType,
          });
        });

        // 添加事件监听
        this.player.on('loadstart', () => {
          console.log('开始加载视频');
        });

        this.player.on('loadedmetadata', () => {
          console.log('视频元数据已加载');
          this.player.play(); // 可选：自动播放
        });

        this.player.on('error', (error) => {
          const errorDetails = this.player.error();
          console.error('播放器错误:', errorDetails);
          console.log(error);
          if (this.retryCount < this.maxRetries) {
            // this.retryCount++;
            console.log(`重试第 ${this.retryCount} 次`);
            setTimeout(() => this.handleRetry(), 1000);
          } else {
            this.handleError('视频加载失败，请检查网络连接或稍后重试');
          }
        });

        this.player.on('ready', () => {
          console.log('播放器就绪');
          this.player.addClass('vjs-custom-theme');
        });
      } catch (error) {
        console.error('播放器初始化错误:', error);
        this.handleError('播放器初始化失败');
      }
    },

    async handleRetry() {
      this.isError = false;
      this.errorMessage = '';
      this.retryCount = 0;
      this.processVideoUrl(this.noteId);
      await this.$nextTick();
      await this.initializePlayer();
    },
  },
};
</script>

<style lang="less" scoped>
.video-player {
  width: 100%;
  aspect-ratio: 16/9;
  background: #000;
  position: relative;

  .video-container {
    width: 100%;
    height: 100%;
    position: relative;
  }

  :deep(.video-js) {
    width: 100% !important;
    height: 100% !important;
    position: absolute;
    top: 0;
    left: 0;

    &.vjs-custom-theme {
      .vjs-big-play-button {
        background-color: rgba(0, 0, 0, 0.45);
        border-radius: 50%;
        width: 60px;
        height: 60px;
        line-height: 60px;
        border: none;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }

      .vjs-control-bar {
        background-color: rgba(0, 0, 0, 0.7);
      }

      .vjs-poster {
        background-size: cover;
      }
    }

    video {
      object-fit: contain;
    }
  }

  .error-message {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    color: #fff;
    z-index: 1;
    background: rgba(0, 0, 0, 0.7);
    padding: 20px;
    border-radius: 8px;

    span {
      display: block;
      margin-bottom: 10px;
    }
  }
}
</style>
